class_name TankTurret3D extends Node3D

@export var rotation_speed : float
@export var recoil_force: int
@export var damage: int
@onready var default_damage: int

var turret: Node3D
var aim_rays: Array[RayCast3D]
var barrel_end: Node3D
var shot_sound: AudioStreamPlayer3D

var explosion_effect = load("res://Scenes/explosion_effect.tscn")

func _ready():
	default_damage = damage
	for child in get_children():
		if child is RayCast3D:
			aim_rays.append(child)
		if child.name.contains("BarrelEnd"):
			barrel_end = child
		if child.name.contains("ShotAudio"):
			shot_sound = child
	
	turret = barrel_end.owner

func rotate_left(delta):
	turret.rotate_y(rotation_speed * delta)

func rotate_right(delta):
	turret.rotate_y(-rotation_speed * delta)
	
func apply_recoil():
	var turret_forward = turret.global_transform.basis.z.normalized()
	get_parent().apply_impulse(turret_forward * recoil_force, turret.position)

func hitscan_target():
	var target_array = []
	var found_enemies = []
	var closest_enemy = null
	var main_aim_ray = aim_rays[0]
	
	if main_aim_ray.is_colliding():
		var target = main_aim_ray.get_collider()
		var target_coordinates = main_aim_ray.get_collision_point()
		var distance_to_target = barrel_end.position.distance_to(target_coordinates)
		var main_ray_target = [target, distance_to_target, target_coordinates, main_aim_ray]
		if main_ray_target[0].get_class() == "VehicleBody3D" or main_ray_target[0].get_class() == "StaticBody3D":
			return main_ray_target
	
	for aim_ray in aim_rays:
		if aim_ray.is_colliding():
			var target = aim_ray.get_collider()
			var target_coordinates = aim_ray.get_collision_point()
			var distance_to_target = barrel_end.position.distance_to(target_coordinates)
			target_array.append([target, distance_to_target, target_coordinates, aim_ray])
			
		for target in target_array:
			if target[0].get_class() == "VehicleBody3D" or target[0].get_class() == "StaticBody3D":
				found_enemies.append(target)
	
	if found_enemies:
		closest_enemy = found_enemies[0]
		for enemy in found_enemies:
			if enemy[1] < closest_enemy[1]:
				closest_enemy = enemy
		
	if closest_enemy:
		return closest_enemy
	else:
		return main_aim_ray.get_collision_point()

@rpc("call_local")
func apply_explosion(collision_point):
	var explosion = explosion_effect.instantiate()
	explosion.emitting = true
	get_parent().get_parent().add_child(explosion)
	explosion.global_transform.origin = collision_point
	await get_tree().create_timer(1).timeout
	explosion.queue_free()

@rpc("call_local")
func play_shot_sound():
	shot_sound.play()
